﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using TFC;

namespace StepControl
{
    public partial class Form1 : Form
    {

        USBHandler Communicator = new USBHandler();
        bool connected = false;
        bool template1 = false;
        bool template2 = false;
        
        public Form1()
        {
            InitializeComponent();
            Communicator.MessageReceivedEvent += new USBHandler.MessageReceivedDelegate(Communicator_MessageReceivedEvent);
        }

        void Communicator_MessageReceivedEvent(string message)
        {
            int CommaPosition = message.IndexOf(',');
            string Parameter = message.Substring(CommaPosition + 1, message.Length - CommaPosition - 2);
            string MessageToParse = message.Substring(0, message.Length - Parameter.Length - 2);
            //MessageBox.Show(message);
            switch (MessageToParse)
            {
                case "INFO(CONNECTED":
                    this.Invoke((MethodInvoker)delegate { label_ConnctionStatusData.Text = "Device found and connected"; }); // runs on UI thread  
                    this.Invoke((MethodInvoker)delegate { label_ConnctionStatusData.ForeColor = Color.Silver; }); // runs on UI thread 
                    this.Invoke((MethodInvoker)delegate { button_Connect.Text = "Disconnect"; }); // runs on UI thread
                    connected = true;
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Connect_Click(object sender, EventArgs e)
        {
            try
            {
                if (!connected)
                {
                    if (Communicator.OpenCommunication(short.Parse(comboBox_ComPort.Text.Remove(0, 3))))
                    {
                        Communicator.SendCommand("SET(CONNECTED)\r\n");
                    }
                }
                else
                    if (Communicator.CloseCommunication())
                    {
                        button_Connect.Text = "Connect";
                        label_ConnctionStatusData.Text = "Disconnected";
                        label_ConnctionStatusData.ForeColor = Color.Red;
                        connected = false;
                    }
            }
            catch { }
        }

        private void UpdateCOMPortList()
        {
            int i;
            bool foundDifference;

            i = 0;
            foundDifference = false;

            //If the number of COM ports is different than the last time we
            //  checked, then we know that the COM ports have changed and we
            //  don't need to verify each entry.
            if (comboBox_ComPort.Items.Count == SerialPort.GetPortNames().Length)
            {
                //Search the entire SerialPort object.  Look at COM port name
                //  returned and see if it already exists in the list.
                foreach (string s in SerialPort.GetPortNames())
                {
                    //If any of the names have changed then we need to update 
                    //  the list
                    if (comboBox_ComPort.Items[i++].Equals(s) == false)
                    {
                        foundDifference = true;
                    }
                }
            }
            else
            {
                foundDifference = true;
            }

            //If nothing has changed, exit the function.
            if (foundDifference == false)
            {
                return;
            }

            //If something has changed, then clear the list
            comboBox_ComPort.Items.Clear();

            //Add all of the current COM ports to the list
            foreach (string s in SerialPort.GetPortNames())
            {
                comboBox_ComPort.Items.Add(s);
            }
            //Set the listbox to point to the first entry in the list
            comboBox_ComPort.SelectedIndex = 0;
        }

        private void comboBox_ComPort_Click(object sender, EventArgs e)
        {
            UpdateCOMPortList();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Communicator.CloseCommunication();
        }

        private void buttonFreRunM1_Click(object sender, EventArgs e)
        {
           
            if (radioButtonM1CW.Checked)
            Communicator.SendCommand("SET(M1_DIRCW,1)\r\n");
            else if (radioButtonM1CCW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,0)\r\n");
            Communicator.SendCommand("SET(M1_SPEED," + comboBoxM1Speed.Text + ")\r\n");
        }

        private void buttonFreeRunM2_Click(object sender, EventArgs e)
        {
           
            if (radioButtonM2CW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,1)\r\n");
            else if (radioButtonM2CCW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,0)\r\n");
            Communicator.SendCommand("SET(M2_SPEED," + comboBoxM2Speed.Text + ")\r\n");
        }

        private void buttonStepRunM1_Click(object sender, EventArgs e)
        {
           
            if (radioButtonM1CW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,1)\r\n");
            else if (radioButtonM1CCW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,0)\r\n");
            Communicator.SendCommand("SET(M1STEPNR," + comboBoxM1Step.Text + ")\r\n");
        }

        private void buttonStepRunM2_Click(object sender, EventArgs e)
        {
            
            if (radioButtonM2CW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,1)\r\n");
            else if (radioButtonM2CCW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,0)\r\n");
            Communicator.SendCommand("SET(M2STEPNR," + comboBoxM2Step.Text + ")\r\n");
        }

        private void buttonSetAngleM1_Click(object sender, EventArgs e)
        {
            int angle = 0;
            angle = int.Parse(comboBoxM1Angle.Text) / 18;
            if (radioButtonM1CW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,1)\r\n");
            else if (radioButtonM1CCW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,0)\r\n");
            Communicator.SendCommand("SET(M1STEPNR," + angle.ToString() + ")\r\n");
        }

        private void buttonSetAngleM2_Click(object sender, EventArgs e)
        {
            int angle = 0;
            angle = int.Parse(comboBoxM2Angle.Text) / 18;
            if (radioButtonM2CW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,1)\r\n");
            else if (radioButtonM2CCW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,0)\r\n");
            Communicator.SendCommand("SET(M2STEPNR," + angle.ToString() + ")\r\n");
        }

        private void buttonM1Stop_Click(object sender, EventArgs e)
        {
            Communicator.SendCommand("SET(M1_STOP,1)\r\n");
        }

        private void buttonM2Stop_Click(object sender, EventArgs e)
        {
            Communicator.SendCommand("SET(M2_STOP,1)\r\n");
        }

        private void buttonTemplateRun1_Click(object sender, EventArgs e)
        {
            groupBoxM1.Enabled = false;
            groupBoxM2.Enabled = false;
            Communicator.SendCommand("SET(M1_SPEED,300)\r\n");
            Communicator.SendCommand("SET(M1_STOP,1)\r\n");
            Communicator.SendCommand("SET(M2_SPEED,300)\r\n");
            Communicator.SendCommand("SET(M2_STOP,1)\r\n");
            timer1.Enabled = true;
            template1 = true;
            template2 = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (template1)
            {

                Communicator.SendCommand("SET(M1_DIRCW,0)\r\n");
                Communicator.SendCommand("SET(M1STEPNR,20)\r\n");

                Communicator.SendCommand("SET(M2_DIRCW,0)\r\n");
                Communicator.SendCommand("SET(M2STEPNR,20)\r\n");

            }

            if (template2)
            {

                Communicator.SendCommand("SET(M1_DIRCW,0)\r\n");
                Communicator.SendCommand("SET(M1STEPNR,20)\r\n");
                Thread.Sleep(300);
                Communicator.SendCommand("SET(M2_DIRCW,1)\r\n");
                Communicator.SendCommand("SET(M2STEPNR,20)\r\n");
                Thread.Sleep(300);
            }



        }

        private void buttonTemplateStop_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            groupBoxM1.Enabled = true;
            groupBoxM2.Enabled = true;
        }

        private void buttonTemplateRun2_Click(object sender, EventArgs e)
        {
            groupBoxM1.Enabled = false;
            groupBoxM2.Enabled = false;
            Communicator.SendCommand("SET(M1_SPEED,300)\r\n");
            Communicator.SendCommand("SET(M1_STOP,1)\r\n");
            Communicator.SendCommand("SET(M2_SPEED,300)\r\n");
            Communicator.SendCommand("SET(M2_STOP,1)\r\n");
            timer1.Enabled = true;
            template1 = false;
            template2 = true;
        }

        private void radioButtonM2CW_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonM2CW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,1)\r\n");
            else if (radioButtonM2CCW.Checked)
                Communicator.SendCommand("SET(M2_DIRCW,0)\r\n");
        }

        private void radioButtonM2CCW_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void radioButtonM1CW_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButtonM1CW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,1)\r\n");
            else if (radioButtonM1CCW.Checked)
                Communicator.SendCommand("SET(M1_DIRCW,0)\r\n");
        }

        private void radioButtonM1CCW_CheckedChanged(object sender, EventArgs e)
        {
        }
    }
}
